package cn.xorange.commons.security.filter;

import cn.xorange.commons.security.configuration.SecurityProperties;
import cn.xorange.commons.security.constants.SecurityConstants;
import cn.xorange.commons.security.exception.SecurityErrorCode;

import cn.xorange.commons.security.service.LoginHandler;
import cn.xorange.commons.security.service.LoginHandlerFactory;
import cn.xorange.commons.security.service.SecurityService;
import cn.xorange.commons.utils.captcha.Captcha;
import cn.xorange.commons.utils.captcha.CaptchaService;
import cn.xorange.commons.utils.http.ServletUtils;
import cn.xorange.commons.utils.lang.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author : yangjian
 * @date : 2023/12/17
 */
public class LoginFilterService {

    @Resource
    SecurityProperties securityProperties;
    @Resource
    CaptchaService captchaService;
    @Resource
    SecurityService securityService;


    public LoginHandler getLoginHandler(String sysType,String loginType,LoginHandlerFactory loginHandlerFactory){
        return loginHandlerFactory.getLoginHandler(sysType,loginType);
    }

    public void checkLoginErr(HttpServletResponse response,String source,String loginName, LoginHandler loginHandler){
        Integer maxErrNum = loginHandler.config().getErrNum();
        Integer errNum = securityService.getLoginErr(source,loginName);
        if(errNum > maxErrNum){
            SecurityErrorCode code = SecurityErrorCode.AUTH_USERNAME_OR_PWD_ERROR;
            String msg = StringUtils.format("密码连续输错大于{}次，请{}分钟后重试", maxErrNum, loginHandler.config().getClockTime()/60);
            ServletUtils.responseOut(response,code.getStatus(),code.getCode(),msg,null);
        }
    }

    public boolean enableCaptcha(LoginHandler loginHandler){
        boolean isEnable = false;
        if(Objects.nonNull(loginHandler)) {
            isEnable = loginHandler.config().getEnableCaptcha();
        }else {
            isEnable = this.securityProperties.getEnableCaptcha();
        }
        return isEnable;
    }

    public Captcha checkCaptcha(String code, String uuid){
        return captchaService.checkCaptcha(uuid, code);
    }

    public String checkSuperUserLogin(String staffId){
        for(String userName : securityProperties.getSuperUserNames()){
            if(userName.equals(staffId)){
                return SecurityConstants.FLAG_YES;
            }
        }
        return SecurityConstants.FLAG_NO;
    }


}
